/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my12306.ocr;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.TessAPI;
import net.sourceforge.tess4j.Tesseract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jack
 */
public class OCR {

    final static Logger logger = LoggerFactory.getLogger(OCR.class.getClass());
//    static Tesseract instance = Tesseract.getInstance();
    static Tesseract instance = null;

    static {
        try {
            instance = Tesseract.getInstance();
            instance.setDatapath(new File(".", "tessdata").getAbsolutePath());
        } catch (Exception ex) {
            logger.error(ex.getLocalizedMessage(), ex);
        } catch (Error ex) {
            logger.error(ex.getLocalizedMessage(), ex);
        }
    }

    public static String doOCR(BufferedImage image) {
        String result = "";
        try {
            if (image == null) {
                return result;
            }
            logger.info("OCR Starting...");
            instance.setLanguage("eng");
            instance.setOcrEngineMode(TessAPI.TessOcrEngineMode.OEM_DEFAULT);
            instance.setPageSegMode(TessAPI.TessPageSegMode.PSM_SINGLE_LINE);
            result = instance.doOCR(image).trim();
            logger.info("OCR result: {}", result);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } catch (Error ex) {
            logger.error(ex.getMessage(), ex);
        }
        return result;
    }

    public static String doOCR(byte[] buffer) {
        String result = "";
        BufferedImage image = null;
        try {
            if (buffer.length <= 0) {
                return result;
            }
            image = ImageIO.read(new ByteArrayInputStream(buffer));
            return doOCR(image);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } catch (Error ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            image = null;
        }
        return result.trim();
    }
}
